//------------------------------------------------------------------------------
#include <QtDebug>
#include "CCrypt.h"
//------------------------------------------------------------------------------
QString CCrypt::reverse(QString str)
{
	QString ret="";
	
	for(int i=str.size()-1;i>=0;i--)
	{
		ret+=str.at(i);
	}
	
	return ret;
}
//------------------------------------------------------------------------------
QString CCrypt::crypt(QString str)
{
	int i, j;
	QByteArray src(str.toUtf8());
	QByteArray dest;
	QString sCrypt;
	int idxE;
	
	for(i=0;i<src.size();i++)
	{
		unsigned res=(unsigned)((src.at(i) ^ mask)+add);
		char *c=(char *)&res;
		for(j=0;j<(int)sizeof(unsigned);j++)
		{
			dest.append(c[j]);
		}
	}
	
	sCrypt=QString(dest.toBase64());
	
	if((idxE=sCrypt.indexOf("=")) != -1)
	{
		int l=sCrypt.length();
		sCrypt=sCrypt.left(idxE)+QString::number(l-idxE);
	}else
	{
		sCrypt+="0";
	}
	
	sCrypt=reverse(sCrypt);
	sCrypt.replace("AAAA", "$");
	
	return sCrypt;;
}
//------------------------------------------------------------------------------
QString CCrypt::decrypt(QString str)
{
	int i, j;
	
	str=reverse(str);
	str.replace("$", "AAAA");

	int end=str.right(1).toInt();
	str=str.remove(str.size()-1, 1)+QString("=").repeated(end);
	QByteArray src(QByteArray::fromBase64(str.toAscii()));
	QByteArray dest;
	
	for(i=0;i<src.size();i+=(int)sizeof(unsigned))
	{
		unsigned res;
		char *c=(char *)&res;
		for(j=i;j<i+(int)sizeof(unsigned);j++)
		{
			c[j-i]=src.at(j);
		}
		dest.append((char)((res-add) ^ mask));
	}
	
	return QString(dest);
}
//------------------------------------------------------------------------------